package org.amphiprion.montrictracv4.fragment;

import java.util.List;

import org.amphiprion.montrictracv4.MainActivity;
import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.adapter.LudothequeListAdapter;
import org.amphiprion.montrictracv4.db.dao.LudothequeDao;
import org.amphiprion.montrictracv4.db.model.Ludotheque;
import org.amphiprion.montrictracv4.db.model.LudothequeGame;
import org.amphiprion.montrictracv4.swipe.SwipeDismissListViewTouchListener;
import org.amphiprion.montrictracv4.swipe.UndoBarController;
import org.amphiprion.montrictracv4.swipe.UndoBarController.UndoContent;
import org.amphiprion.montrictracv4.swipe.UndoBarController.UndoListener;
import org.amphiprion.montrictracv4.task.ludotheque.SynchronizeLudothequeTask;
import org.amphiprion.montrictracv4.task.ludotheque.SynchronizeLudothequeTask.SynchronizeLudothequeListener;
import org.amphiprion.montrictracv4.thread.MemberCompletion;
import org.amphiprion.montrictracv4.thread.MemberCompletion.MemberCompletionHandler;
import org.amphiprion.montrictracv4.web.adapter.ImageAndLabelListAdapter;
import org.amphiprion.montrictracv4.web.adapter.ImageAndLabelListItem;
import org.amphiprion.montrictracv4.web.model.Member;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class LudothequeFragment extends SherlockFragment implements TricTracFragment, UndoListener {
	private View fragment;
	private LayoutInflater mInflater;
	private SherlockFragmentActivity context;
	private ListView listView;
	private LudothequeListAdapter adapter;
	private UndoBarController undoBarController;

	public LudothequeFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
		super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);

		this.context = getSherlockActivity();
		this.mInflater = paramLayoutInflater;
		this.fragment = paramLayoutInflater.inflate(R.layout.fragment_ludotheque, null);
		this.listView = ((ListView) this.fragment.findViewById(R.id.lstLudotheque));
		this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View arg1, int row, long arg3) {
				Ludotheque ludotheque = (Ludotheque) adapter.getItemAtPosition(row);
				((MainActivity) getActivity()).showGameList(ludotheque);
			}
		});

		SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(listView, new SwipeDismissListViewTouchListener.OnDismissCallback() {
			@Override
			public void onDismiss(ListView listView, int[] reverseSortedPositions) {
				for (int position : reverseSortedPositions) {
					if (position < adapter.getCount()) {
						Ludotheque ludo = adapter.getItem(position);
						adapter.remove(ludo);
						undoBarController.showUndoBar(false, ludo.name, ludo, position);
					}
				}
				adapter.notifyDataSetChanged();
			}
		});
		listView.setOnTouchListener(touchListener);
		// Setting this scroll listener is required to ensure that during ListView scrolling,
		// we don't look for swipes.
		listView.setOnScrollListener(touchListener.makeScrollListener());

		undoBarController = new UndoBarController(this.fragment.findViewById(R.id.undobar), this);

		return this.fragment;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initData();
	}

	public void initData() {
		List<Ludotheque> ludos = LudothequeDao.getInstance(context).getLudoteques();
		adapter = new LudothequeListAdapter(context, this, R.layout.ludotheque_item_row, ludos);
		listView.setAdapter(adapter);
	}

	@Override
	public void menuOptionClicked(int id) {
		switch (id) {
		case R.id.action_add:
			askMemberName();
			break;
		}
	}

	private void askMemberName() {
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.searcheable_list);
		dialog.setTitle(getResources().getString(R.string.pseudo));
		final EditText txtSearch = (EditText) dialog.findViewById(R.id.txtSearch);
		final ListView lstMembers = (ListView) dialog.findViewById(R.id.listSearchResult);
		lstMembers.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> view, View arg1, int row, long id) {
				txtSearch.setText(lstMembers.getItemAtPosition(row).toString());
				dialog.dismiss();
				addLudotheque((Member) lstMembers.getItemAtPosition(row), null);
			}
		});

		txtSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.toString().length() >= 2) {
					if (txtSearch.getTag() != null) {
						((MemberCompletion) txtSearch.getTag()).cancel();
					}
					MemberCompletion mc = new MemberCompletion(s.toString(), new MemberCompletionHandler() {
						@Override
						public void listRetrieved(List<ImageAndLabelListItem> members) {
							final ImageAndLabelListAdapter adapter = new ImageAndLabelListAdapter(context, R.layout.listview_item_row, members);
							// View header =
							// getLayoutInflater().inflate(R.layout.listview_header_row,
							// null);
							// lstMembers.addHeaderView(header);
							context.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									lstMembers.setAdapter(adapter);
								}
							});
						}
					});
					txtSearch.setTag(mc);
					new Thread(mc).start();
				}
			}
		});
		dialog.show();
	}

	public void addLudotheque(Member member, Ludotheque ludotheque) {
		SynchronizeLudothequeTask task = new SynchronizeLudothequeTask(context, member, new SynchronizeLudothequeListener() {
			@Override
			public void importEnded(boolean succeed, List<LudothequeGame> result) {
				if (succeed) {
					initData();
				}
			}
		});

		task.execute(ludotheque);
	}

	@Override
	public void refresh() {
		initData();
	}

	@Override
	public void onUndo(List<UndoContent> undoContents) {
		for (UndoContent uc : undoContents) {
			adapter.add(uc.position, (Ludotheque) uc.param);
		}
		adapter.notifyDataSetChanged();

	}

	@Override
	public void onNotUndo(List<UndoContent> undoContents) {
		for (UndoContent uc : undoContents) {
			LudothequeDao.getInstance(context).delete((Ludotheque) uc.param);
		}
	}
}
